package me.zhengjie.modules.mnprogram.service.impl;

import me.zhengjie.modules.mnprogram.bo.NewCoderBO;
import me.zhengjie.modules.mnprogram.domain.NewCoderDTO;
import me.zhengjie.modules.mnprogram.repository.NewCoderRepository;
import me.zhengjie.modules.mnprogram.service.NewCoderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Service
public class NewCoderServiceImpl implements NewCoderService {

    @Autowired
    NewCoderRepository newCoderRepository;

    @Override
    public NewCoderDTO insertNewCoder(NewCoderBO newCoderBO) {
        NewCoderDTO newCoderDTO = new NewCoderDTO();
        BeanUtils.copyProperties(newCoderBO,newCoderDTO);
        if (StringUtils.isNotBlank(newCoderBO.getCreateTime())){
            newCoderDTO.setCreateTime(newCoderBO.getCreateTime());
        }else {
            newCoderDTO.setCreateTime(LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli()+"");
        }
        newCoderDTO.setViewNum(0L);
        newCoderRepository.save(newCoderDTO);
        newCoderBO.setId(newCoderDTO.getId());
        return newCoderDTO;
    }

    @Override
    public NewCoderDTO updateNewCoder(NewCoderBO newCoderBO) {
        NewCoderDTO newCoderDTO = newCoderRepository.findById(newCoderBO.getId()).get();
        if(StringUtils.isNoneBlank(newCoderBO.getBrief())){
            newCoderDTO.setBrief(newCoderBO.getBrief());
        }
        if(StringUtils.isNoneBlank(newCoderBO.getLabel())){
            newCoderDTO.setLabel(newCoderBO.getLabel());
        }
        if(StringUtils.isNoneBlank(newCoderBO.getContent())){
            newCoderDTO.setContent(newCoderBO.getContent());
        }
        if(StringUtils.isNoneBlank(newCoderBO.getTitle())){
            newCoderDTO.setTitle(newCoderBO.getTitle());
        }
        if(StringUtils.isNoneBlank(newCoderBO.getType())){
            newCoderDTO.setType(newCoderBO.getType());
        }
        newCoderRepository.save(newCoderDTO);
        return newCoderDTO;
    }
}
